<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/11
 * Time: 16:42
 */

namespace iBrand\Shop\Core\Listeners;


use iBrand\Component\Order\Models\Order;
use iBrand\Component\Point\Model\Point;
use iBrand\Shop\Core\Models\ShopOrder;
use iBrand\Shop\Core\Models\ShopPoint;

class OrderEventListener
{

    public function onOrderCompleted(Order $order)
    {
        $item_ids = $order->getItems()->pluck('id')->toArray();
        $shopOrder = ShopOrder::where('order_id', $order->id)->first();

        $points = Point::whereIn('item_id', $item_ids)->get();
        if (count($points) > 0) {
            foreach ($points as $point) {
                $point->status = 1;
                $point->save();

                if ($shopOrder) {
                    ShopPoint::create([
                        'point_id' => $point->id,
                        'shop_id' => $shopOrder->shop_id
                    ]);
                }
            }
        }
    }

    public function onOrderCanceled($order_id)
    {
        $order = Order::find($order_id);
        if($order AND $order->channel=='shop'){
            foreach ($order->getItems() as $item) {
                $model = $item->type;
                $model = new $model();
                $product = $model->find($item->item_id)->getO2oProduct($order->channel_id);
                $product->reduceStock($item->quantity);
                $product->increaseSales($item->quantity);
                $product->save();
            }
        }
    }

    public function subscribe($events)
    {
        $events->listen(
            'shop.order.completed',
            'iBrand\Shop\Core\Listeners\OrderEventListener@onOrderCompleted'
        );
        $events->listen(
            'order.canceled',
            'iBrand\Shop\Core\Listeners\OrderEventListener@onOrderCanceled'
        );

    }
}